<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Eigen: Adding a new expression type</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
  $(document).ready(function() { init_search(); });
/* @license-end */
</script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
</script>
<script type="text/javascript" async="async" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="eigendoxy.css" rel="stylesheet" type="text/css">
<!--  -->
<script type="text/javascript" src="eigen_navtree_hacks.js"></script>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="Eigen_Silly_Professor_64x64.png"/></td>
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname"><a href="http://eigen.tuxfamily.org">Eigen</a>
   &#160;<span id="projectnumber">3.4.90 (git rev 67eeba6e720c5745abc77ae6c92ce0a44aa7b7ae)</span>
   </div>
  </td>
   <td>        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <img id="MSearchSelect" src="search/mag_sel.svg"
               onmouseover="return searchBox.OnSearchSelectShow()"
               onmouseout="return searchBox.OnSearchSelectHide()"
               alt=""/>
          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.svg" alt=""/></a>
          </span>
        </div>
</td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
      <div id="nav-sync" class="sync"></div>
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('TopicNewExpressionType.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="PageDoc"><div class="header">
  <div class="headertitle">
<div class="title">Adding a new expression type </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><dl class="section warning"><dt>Warning</dt><dd>Disclaimer: this page is tailored to very advanced users who are not afraid of dealing with some Eigen's internal aspects. In most cases, a custom expression can be avoided by either using custom unary or binary functors, while extremely complex matrix manipulations can be achieved by a nullary functors as described in the <a class="el" href="TopicCustomizing_NullaryExpr.html">previous page</a>.</dd></dl>
<p>This page describes with the help of an example how to implement a new light-weight expression type in Eigen. This consists of three parts: the expression type itself, a traits class containing compile-time information about the expression, and the evaluator class which is used to evaluate the expression to a matrix.</p>
<p><b>TO</b> <b>DO:</b> Write a page explaining the design, with details on vectorization etc., and refer to that page here.</p>
<h1><a class="anchor" id="TopicSetting"></a>
The setting</h1>
<p>A circulant matrix is a matrix where each column is the same as the column to the left, except that it is cyclically shifted downwards. For example, here is a 4-by-4 circulant matrix: </p><p class="formulaDsp">
\[ \begin{bmatrix} 1 &amp; 8 &amp; 4 &amp; 2 \\ 2 &amp; 1 &amp; 8 &amp; 4 \\ 4 &amp; 2 &amp; 1 &amp; 8 \\ 8 &amp; 4 &amp; 2 &amp; 1 \end{bmatrix} \]
</p>
<p> A circulant matrix is uniquely determined by its first column. We wish to write a function <code>makeCirculant</code> which, given the first column, returns an expression representing the circulant matrix.</p>
<p>For simplicity, we restrict the <code>makeCirculant</code> function to dense matrices. It may make sense to also allow arrays, or sparse matrices, but we will not do so here. We also do not want to support vectorization.</p>
<h1><a class="anchor" id="TopicPreamble"></a>
Getting started</h1>
<p>We will present the file implementing the <code>makeCirculant</code> function part by part. We start by including the appropriate header files and forward declaring the expression class, which we will call <code>Circulant</code>. The <code>makeCirculant</code> function will return an object of this type. The class <code>Circulant</code> is in fact a class template; the template argument <code>ArgType</code> refers to the type of the vector passed to the <code>makeCirculant</code> function.</p>
<div class="fragment"><div class="line">#include &lt;Eigen/Core&gt;</div>
<div class="line">#include &lt;iostream&gt;</div>
<div class="line"> </div>
<div class="line">template &lt;class ArgType&gt; class Circulant;</div>
</div><!-- fragment --><h1><a class="anchor" id="TopicTraits"></a>
The traits class</h1>
<p>For every expression class <code>X</code>, there should be a traits class <code>Traits&lt;X&gt;</code> in the <code>Eigen::internal</code> namespace containing information about <code>X</code> known as compile time.</p>
<p>As explained in <a class="el" href="TopicNewExpressionType.html#TopicSetting">The setting</a>, we designed the <code>Circulant</code> expression class to refer to dense matrices. The entries of the circulant matrix have the same type as the entries of the vector passed to the <code>makeCirculant</code> function. The type used to index the entries is also the same. Again for simplicity, we will only return column-major matrices. Finally, the circulant matrix is a square matrix (number of rows equals number of columns), and the number of rows equals the number of rows of the column vector passed to the <code>makeCirculant</code> function. If this is a dynamic-size vector, then the size of the circulant matrix is not known at compile-time.</p>
<p>This leads to the following code:</p>
<div class="fragment"><div class="line">namespace Eigen {</div>
<div class="line">  namespace internal {</div>
<div class="line">    template &lt;class ArgType&gt;</div>
<div class="line">    struct traits&lt;Circulant&lt;ArgType&gt; &gt;</div>
<div class="line">    {</div>
<div class="line">      typedef Eigen::Dense StorageKind;</div>
<div class="line">      typedef Eigen::MatrixXpr XprKind;</div>
<div class="line">      typedef typename ArgType::StorageIndex StorageIndex;</div>
<div class="line">      typedef typename ArgType::Scalar Scalar;</div>
<div class="line">      enum { </div>
<div class="line">        Flags = Eigen::ColMajor,</div>
<div class="line">        RowsAtCompileTime = ArgType::RowsAtCompileTime,</div>
<div class="line">        ColsAtCompileTime = ArgType::RowsAtCompileTime,</div>
<div class="line">        MaxRowsAtCompileTime = ArgType::MaxRowsAtCompileTime,</div>
<div class="line">        MaxColsAtCompileTime = ArgType::MaxRowsAtCompileTime</div>
<div class="line">      };</div>
<div class="line">    };</div>
<div class="line">  }</div>
<div class="line">}</div>
</div><!-- fragment --><h1><a class="anchor" id="TopicExpression"></a>
The expression class</h1>
<p>The next step is to define the expression class itself. In our case, we want to inherit from <code><a class="el" href="classEigen_1_1MatrixBase.html" title="Base class for all dense matrices, vectors, and expressions.">MatrixBase</a></code> in order to expose the interface for dense matrices. In the constructor, we check that we are passed a column vector (see <a class="el" href="TopicAssertions.html">Assertions</a>) and we store the vector from which we are going to build the circulant matrix in the member variable <code>m_arg</code>. Finally, the expression class should compute the size of the corresponding circulant matrix. As explained above, this is a square matrix with as many columns as the vector used to construct the matrix.</p>
<p><b>TO</b> <b>DO:</b> What about the <code>Nested</code> typedef? It seems to be necessary; is this only temporary?</p>
<div class="fragment"><div class="line">template &lt;class ArgType&gt;</div>
<div class="line">class Circulant : public Eigen::MatrixBase&lt;Circulant&lt;ArgType&gt; &gt;</div>
<div class="line">{</div>
<div class="line">public:</div>
<div class="line">  Circulant(const ArgType&amp; arg)</div>
<div class="line">    : m_arg(arg)</div>
<div class="line">  { </div>
<div class="line">    EIGEN_STATIC_ASSERT(ArgType::ColsAtCompileTime == 1,</div>
<div class="line">                        YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX);</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  typedef typename Eigen::internal::ref_selector&lt;Circulant&gt;::type Nested; </div>
<div class="line"> </div>
<div class="line">  typedef Eigen::Index Index;</div>
<div class="line">  Index rows() const { return m_arg.rows(); }</div>
<div class="line">  Index cols() const { return m_arg.rows(); }</div>
<div class="line"> </div>
<div class="line">  typedef typename Eigen::internal::ref_selector&lt;ArgType&gt;::type ArgTypeNested;</div>
<div class="line">  ArgTypeNested m_arg;</div>
<div class="line">};</div>
</div><!-- fragment --><h1><a class="anchor" id="TopicEvaluator"></a>
The evaluator</h1>
<p>The last big fragment implements the evaluator for the <code>Circulant</code> expression. The evaluator computes the entries of the circulant matrix; this is done in the <code></code>.coeff() member function. The entries are computed by finding the corresponding entry of the vector from which the circulant matrix is constructed. Getting this entry may actually be non-trivial when the circulant matrix is constructed from a vector which is given by a complicated expression, so we use the evaluator which corresponds to the vector.</p>
<p>The <code>CoeffReadCost</code> constant records the cost of computing an entry of the circulant matrix; we ignore the index computation and say that this is the same as the cost of computing an entry of the vector from which the circulant matrix is constructed.</p>
<p>In the constructor, we save the evaluator for the column vector which defined the circulant matrix. We also save the size of that vector; remember that we can query an expression object to find the size but not the evaluator.</p>
<div class="fragment"><div class="line">namespace Eigen {</div>
<div class="line">  namespace internal {</div>
<div class="line">    template&lt;typename ArgType&gt;</div>
<div class="line">    struct evaluator&lt;Circulant&lt;ArgType&gt; &gt;</div>
<div class="line">      : evaluator_base&lt;Circulant&lt;ArgType&gt; &gt;</div>
<div class="line">    {</div>
<div class="line">      typedef Circulant&lt;ArgType&gt; XprType;</div>
<div class="line">      typedef typename nested_eval&lt;ArgType, XprType::ColsAtCompileTime&gt;::type ArgTypeNested;</div>
<div class="line">      typedef remove_all_t&lt;ArgTypeNested&gt; ArgTypeNestedCleaned;</div>
<div class="line">      typedef typename XprType::CoeffReturnType CoeffReturnType;</div>
<div class="line"> </div>
<div class="line">      enum { </div>
<div class="line">        CoeffReadCost = evaluator&lt;ArgTypeNestedCleaned&gt;::CoeffReadCost,</div>
<div class="line">        Flags = Eigen::ColMajor </div>
<div class="line">      };</div>
<div class="line">      </div>
<div class="line">      evaluator(const XprType&amp; xpr)</div>
<div class="line">        : m_argImpl(xpr.m_arg), m_rows(xpr.rows())</div>
<div class="line">      { }</div>
<div class="line"> </div>
<div class="line">      CoeffReturnType coeff(Index row, Index col) const</div>
<div class="line">      {</div>
<div class="line">        Index index = row - col;</div>
<div class="line">        if (index &lt; 0) index += m_rows;</div>
<div class="line">        return m_argImpl.coeff(index);</div>
<div class="line">      }</div>
<div class="line"> </div>
<div class="line">      evaluator&lt;ArgTypeNestedCleaned&gt; m_argImpl;</div>
<div class="line">      const Index m_rows;</div>
<div class="line">    };</div>
<div class="line">  }</div>
<div class="line">}</div>
</div><!-- fragment --><h1><a class="anchor" id="TopicEntry"></a>
The entry point</h1>
<p>After all this, the <code>makeCirculant</code> function is very simple. It simply creates an expression object and returns it.</p>
<div class="fragment"><div class="line">template &lt;class ArgType&gt;</div>
<div class="line">Circulant&lt;ArgType&gt; makeCirculant(const Eigen::MatrixBase&lt;ArgType&gt;&amp; arg)</div>
<div class="line">{</div>
<div class="line">  return Circulant&lt;ArgType&gt;(arg.derived());</div>
<div class="line">}</div>
</div><!-- fragment --><h1><a class="anchor" id="TopicMain"></a>
A simple main function for testing</h1>
<p>Finally, a short <code>main</code> function that shows how the <code>makeCirculant</code> function can be called.</p>
<div class="fragment"><div class="line">int main()</div>
<div class="line">{</div>
<div class="line">  Eigen::VectorXd vec(4);</div>
<div class="line">  vec &lt;&lt; 1, 2, 4, 8;</div>
<div class="line">  Eigen::MatrixXd mat;</div>
<div class="line">  mat = makeCirculant(vec);</div>
<div class="line">  std::cout &lt;&lt; mat &lt;&lt; std::endl;</div>
<div class="line">}</div>
</div><!-- fragment --><p>If all the fragments are combined, the following output is produced, showing that the program works as expected:</p>
<div class="fragment"><div class="line">1 8 4 2</div>
<div class="line">2 1 8 4</div>
<div class="line">4 2 1 8</div>
<div class="line">8 4 2 1</div>
</div><!-- fragment --> </div></div><!-- contents -->
</div><!-- PageDoc -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer">Generated on Thu Apr 21 2022 13:07:55 for Eigen by
    <a href="http://www.doxygen.org/index.html">
    <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.9.1 </li>
  </ul>
</div>
</body>
</html>
